package com.first.core.util;

import java.util.Date;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class MailSender {
	
	
	public static void main(String[] args) {
		try {
			MailSender.sendEmail("420915201@qq.com", "MailSender", "MailSender Testing 。。。。");
		} catch (Exception e) {
			System.out.println("上传文件时写入文件错误!" + e.toString());
		}
	}
	

	/**
	 * 发送邮件  返回boolean 类型 设置为三个参数 收件人邮箱地址      邮件主题        邮件内容
	 * @throws Exception 
	 * */  
	public static boolean sendEmail(String toMail,String toTitle,String content){
		boolean flag = false;
		Transport transport = null;
		try {
			Properties props=new Properties();				//也可用Properties props = System.getProperties(); 
			props.put("mail.smtp.host","163.com");		//存储发送邮件服务器的信息
			props.put("mail.smtp.auth","true");				//同时通过验证
			Session s=Session.getInstance(props);			//根据属性新建一个邮件会话
			s.setDebug(true);
			
			MimeMessage message=new MimeMessage(s);			//由邮件会话新建一个消息对象 
			
			//设置邮件
			InternetAddress from=new InternetAddress("420915201@163.com");
			from.setPersonal("习赢网");	//设置发件名字
			message.setFrom(from);		//设置发件人
			
			InternetAddress to=new InternetAddress(toMail);
			message.setRecipient(Message.RecipientType.TO,to);	//设置收件人,并设置其接收类型为TO
			message.setSubject(toTitle);						//设置主题
			//message.setText(content.toString(),"text/html;charset=gbk");//设置信件内容
			message.setSentDate(new Date());					//设置发信时间
			
			BodyPart bodyPart=new MimeBodyPart();				//新建一个存放信件内容的BodyPart对象
			bodyPart.setContent(content, "text/html;charset=UTF-8");//给BodyPart对象设置内容和格式/编码方式
			Multipart multipart =new MimeMultipart();			//新建一个MimeMultipart对象用来存放BodyPart对 象(事实上可以存放多个)			
			multipart.addBodyPart(bodyPart);					//将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
			message.setContent(multipart);						//把mm作为消息对象的内容
			
			
			//发送邮件
			message.saveChanges();//存储邮件信息
			transport=s.getTransport("smtp");
			//transport.connect(host, port, user, password)		
			transport.connect("smtp.163.com","420915201","420915201h");//以smtp方式登录邮箱
			transport.sendMessage(message, message.getAllRecipients());//发送邮件,其中第二个参数是所有
			
			//已设好的收件人地址
			flag = true;
			
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.toString());
		}finally{
			if(transport != null){
				try{
					transport.close();
				}catch(Exception e){
					System.out.println("发送邮件失败");
				}
			}
		}
		
		return flag;
	}
			
}
